package org.snail.proxy.server.http;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

public class HttpClient {
    private static final String CHAR_SET = "UTF-8";
    private static final CloseableHttpClient HTTP_CLIENT = HttpClients.custom()
            .setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName(CHAR_SET)).build())
            .build();

    public static String post(String url, Map<String, String> headers, String content) throws IOException {
        HttpPost request = new HttpPost(url);
        headers.forEach(request::setHeader);
        request.setEntity(new StringEntity(content));
        CloseableHttpResponse response = HTTP_CLIENT.execute(request);
        return EntityUtils.toString(response.getEntity(), CHAR_SET);
    }

    public static String get(String url, Map<String, String> headers) throws IOException {
        HttpGet request = new HttpGet(url);
        headers.forEach(request::setHeader);
        CloseableHttpResponse response = HTTP_CLIENT.execute(request);
        return EntityUtils.toString(response.getEntity(), CHAR_SET);
    }
}
